package com.wxg.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 2020年6月15日15:37:54，
 * 极客时间，
 * <a href="https://baijiahao.baidu.com/s?id=1630163163382081801&wfr=spider&for=pc">大厂不建议使用 Excutors 创建线程池</a>
 */
public class MyThreadPool {
    BlockingQueue<Runnable> workQueue;
    List<WorkerThread> threads = new ArrayList<>();

    MyThreadPool(int poolSize,
                 BlockingQueue<Runnable> workQueue) {
        this.workQueue = workQueue;

        for (int idx = 0; idx < poolSize; idx++) {
            WorkerThread work = new WorkerThread();
            work.start();
            threads.add(work);
        }
    }

    void execute(Runnable command) {
        try {
            workQueue.put(command);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    class WorkerThread extends Thread {
        @Override
        public void run() {
            try {
                while (true) { // (1)
                    Runnable task = workQueue.take();
                    task.run();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        BlockingQueue<Runnable> workQueue =
                new LinkedBlockingQueue<>(2);
        MyThreadPool pool = new MyThreadPool(10, workQueue);
        pool.execute(() -> {
            System.out.println("hello");
        });

        // 大厂不建议使用 Excutors 创建线程池

        ThreadFactory threadFactory = new ThreadFactory() {
            private AtomicLong atomicLong = new AtomicLong(1);
            @Override
            public Thread newThread(Runnable r) {
                String threadName = String.format("MyThread-%d-", atomicLong.getAndIncrement());
                Thread thread = new Thread(r, threadName);
                return thread;
            }
        };

        ExecutorService threadPool = new ThreadPoolExecutor(5, 200,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(1024), threadFactory,
                new ThreadPoolExecutor.AbortPolicy());
    }
}
